package megadict.draft.index;

import static org.junit.Assert.*;
import static java.nio.channels.FileChannel.MapMode.*;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.*;

import org.junit.*;

public class JavaNioLearning {

    @Test
    public void testReadFileUsingByteBuffer() {
        File file = new File("C:/test/av.index");

        int bufferSize = 1024 * 16;
        byte[] rawBytes = new byte[bufferSize];
        ByteBuffer buffer = ByteBuffer.allocateDirect(bufferSize);

        FileChannel reader = makeFileChannel(file);

        int totalLines = 0;
        try {
            while (reader.read(buffer) != -1) {
                buffer.get(rawBytes);
                int lines = countLines(rawBytes);
                totalLines += lines;
            }
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
        final int expectedLines = 108857;
        assertEquals(expectedLines, totalLines);
    }

    private MappedByteBuffer makeByteBuffer(File file) {
        try {
            FileChannel fc = makeFileChannel(file);
            return fc.map(READ_ONLY, 0, file.length());
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
    }

    private FileChannel makeFileChannel(File file) {
        try {
            FileInputStream fis = new FileInputStream(file);
            return fis.getChannel();
        } catch (FileNotFoundException fnf) {
            throw new RuntimeException(fnf);
        }
    }

    private int countLines(byte[] content) {
        int lines = 0;
        int length = content.length;
        for (int i = 0; i < length; i++) {
            if (content[i] == (byte) '\n') {
                lines++;
            }
        }
        return lines;
    }

}
